package com.huike.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.core.domain.entity.SysUser;
import com.huike.dto.ClueDto;
import com.huike.dto.ClueFalseDto;
import com.huike.dto.GainClueDto;
import com.huike.dto.domain.Client;
import com.huike.dto.domain.TbBusiness;
import com.huike.mapper.ClueMapper;
import com.huike.mapper.ClueRecordMapper;
import com.huike.mapper.TbBusinessMapper;
import com.huike.pojo.BusinessOpportunity;
import com.huike.pojo.ClueFollow;
import com.huike.result.PageResult;
import com.huike.service.ClientService;
import com.huike.service.ClueService;
import com.huike.system.service.ISysUserService;
import com.huike.utils.SecurityUtils;
import com.huike.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class ClueServiceImpl extends ServiceImpl<ClueMapper, BusinessOpportunity> implements ClueService {
    private final ClueMapper clueMapper;
    private final ClueRecordMapper clueRecordMapper;
    private final ISysUserService sysUserService;
    private final ClientService clientService;
    private final TbBusinessMapper tbBusinessMapper;
    private final static String BEGIN="beginCreateTime";
    private final static String END="endCreateTime";
    private final static String CLUE_STATUS="1";
    private final static String CLUE_TYPE="1";
    private final static String BUSINESS_TYPE="2";
    private final static String CLUE_NOT_FOLLOW_STATUS="1";//待跟进
    private static final String FALSE_STATUS="4";//伪线索
    public final static String CLUE_FOLLOW_STATUS="2";//跟进中
    private final static String BUSINESS_NOT_FOLLOW_STATUS="1";//待跟进
    @Override
    public PageResult getClueListPage(ClueDto clueDto) {//查询状态为1或0，类型为1的线索
        Page<BusinessOpportunity> page = new Page<>(clueDto.getPageNum(), clueDto.getPageSize());
        LambdaQueryWrapper<BusinessOpportunity> wrapper = new LambdaQueryWrapper<>();
        String beginCreateTime = clueDto.getParams().get(BEGIN);
        String endCreateTime = clueDto.getParams().get(END);
        wrapper.eq(clueDto.getId()!=null,BusinessOpportunity::getId,clueDto.getId());
        wrapper.eq(StringUtils.isNotEmpty(clueDto.getPhone()),BusinessOpportunity::getPhone,clueDto.getPhone());
        wrapper.eq(StringUtils.isNotEmpty(clueDto.getOwner()),BusinessOpportunity::getOwner,clueDto.getOwner());
        wrapper.eq(StringUtils.isNotEmpty(clueDto.getStatus()),BusinessOpportunity::getStatus,clueDto.getStatus());
        if (StringUtils.isNotEmpty(beginCreateTime)&&StringUtils.isNotEmpty(endCreateTime)) {
            wrapper.between(BusinessOpportunity::getCreateTime, beginCreateTime, endCreateTime);
        }
        wrapper.eq(BusinessOpportunity::getType,CLUE_TYPE);
        wrapper.ne(BusinessOpportunity::getStatus,FALSE_STATUS);
        Page<BusinessOpportunity> res = super.page(page, wrapper);
        return new PageResult(res.getTotal(),res.getRecords());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addClue(ClueDto clueDto) {
        BusinessOpportunity businessOpportunity = new BusinessOpportunity();
        String username = SecurityUtils.getUsername();

        //更新客户表
        Client client = new Client();
        BeanUtil.copyProperties(clueDto,client);
        client.setStatus(null);
        clientService.save(client);
        //更新线索表
        BeanUtil.copyProperties(clueDto,businessOpportunity);
        businessOpportunity.setType(CLUE_TYPE);
        businessOpportunity.setOwner(username);
        businessOpportunity.setOwnerTime(LocalDateTime.now());
        businessOpportunity.setAssignBy(username);
        businessOpportunity.setClientId(client.getId());
        super.save(businessOpportunity);
    }

    @Override
    public BusinessOpportunity getClueById(Integer id) {
        return clueMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClueFalseById(Integer id, ClueFalseDto clueFalseDto) {
        //转换成伪线索，status为4，新增操作记录
        clueMapper.updateClueFalseById(id,clueFalseDto);
        ClueFollow clueFollow = new ClueFollow();
        clueFollow.setClueId(id);
        clueFollow.setFalseReason(clueFalseDto.getReason());
        clueFollow.setRecord(clueFalseDto.getRemark());
        clueRecordMapper.insert(clueFollow);
    }

    @Override
    public void gainClueByIds( GainClueDto gainClueDto) {
        //批量捞取，从伪线索转化为线索,status为1,归属人更改，
        LambdaUpdateWrapper<BusinessOpportunity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(BusinessOpportunity::getId,gainClueDto.getIds())
                .set(BusinessOpportunity::getStatus,CLUE_NOT_FOLLOW_STATUS)
                .set(BusinessOpportunity::getOwnerTime,LocalDateTime.now())
                .set(BusinessOpportunity::getOwner,SecurityUtils.getUsername())
                .set(BusinessOpportunity::getNextTime,null);
        clueMapper.update(null,wrapper);
    }

    @Override
    public void assignmentClueByIds(GainClueDto gainClueDto) {
        //批量分配
        SysUser user = sysUserService.selectUserById(gainClueDto.getUserId());
        LambdaUpdateWrapper<BusinessOpportunity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(BusinessOpportunity::getId,gainClueDto.getIds())
                .set(BusinessOpportunity::getOwner,user.getUserName())
                .set(BusinessOpportunity::getAssignBy,SecurityUtils.getUsername())
                .set(BusinessOpportunity::getOwnerTime,LocalDateTime.now());
        clueMapper.update(null,wrapper);
    }

    @Override
    public void changeBusiness(Integer id) {
        //转商机，type为2  新增商机
        BusinessOpportunity clue = clueMapper.selectById(id);
        if (clue!=null){
            clue.setType(BUSINESS_TYPE);
            super.updateById(clue);//线索表类型为2
            TbBusiness tbBusiness = new TbBusiness();
            BeanUtil.copyProperties(clue,tbBusiness);
            tbBusiness.setId(null);
            tbBusiness.setClueId(id.longValue());
            tbBusiness.setCreateTime(LocalDateTime.now());
            tbBusiness.setStatus(BUSINESS_NOT_FOLLOW_STATUS);
            tbBusiness.setNextTime(null);
            tbBusinessMapper.insertTbBusiness(tbBusiness);
        }

    }
}
